using Godot;
using System;

public partial class Enemy : CharacterBody2D
{
	[Export] public float Speed = 100.0f;
	[Export] public int MaxHealth = 80;
	[Export] public int AttackDamage = 15;
	[Export] public float AttackRange = 80.0f;
	[Export] public float AttackCooldown = 2.0f;
	
	private int currentHealth;
	private AnimatedSprite2D animatedSprite;
	private TextureProgressBar healthBar;
	private Area2D hurtBox;
	private Area2D attackArea;
	private CollisionShape2D attackCollision;
	private Vector2 attackAreaOffset;
	
	private Player player;
	private bool isAttacking = false;
	private float attackTimer = 0.0f;
	
	public override void _Ready()
	{
		// 初始化血量
		currentHealth = MaxHealth;
		
		// 获取节点
		animatedSprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
		healthBar = GetNode<TextureProgressBar>("HealthBar");
		hurtBox = GetNode<Area2D>("HurtBox");
		attackArea = GetNode<Area2D>("AttackArea");
		attackCollision = GetNode<CollisionShape2D>("AttackArea/CollisionShape2D");
		
		// 设置血条
		healthBar.MaxValue = MaxHealth;
		healthBar.Value = currentHealth;
		
		// 保存攻击区域的初始偏移量
		attackAreaOffset = attackArea.Position;
		
		// 设置攻击区域组
		attackArea.AddToGroup("enemy_attack");
		
		// 初始时禁用攻击碰撞
		attackCollision.Disabled = true;
		
		// 连接信号
		hurtBox.AreaEntered += OnHurtBoxAreaEntered;
		animatedSprite.AnimationFinished += OnAnimationFinished;
		
		// 添加到敌人组
		AddToGroup("enemy");
		
		// 查找玩家
		player = GetTree().GetFirstNodeInGroup("player") as Player;
		if (player == null)
		{
			GD.PrintErr("找不到玩家节点！请确保玩家节点在'player'组中。");
		}
	}
	
	public override void _PhysicsProcess(double delta)
	{
		if (player == null) return;
		
		// 更新攻击计时器
		if (attackTimer > 0)
		{
			attackTimer -= (float)delta;
		}
		
		// AI行为
		HandleAI(delta);
	}
	
	private void HandleAI(double delta)
	{
		// 获取玩家的实际碰撞体位置
		CollisionShape2D playerCollision = player.GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 playerActualPosition = player.GlobalPosition + playerCollision.Position;
		
		// 获取敌人的实际碰撞体位置
		CollisionShape2D enemyCollision = GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 enemyActualPosition = GlobalPosition + enemyCollision.Position;
		
		// 计算实际碰撞体之间的距离
		float distanceToPlayer = enemyActualPosition.DistanceTo(playerActualPosition);
		
		// 如果在攻击范围内且攻击冷却完成
		if (distanceToPlayer <= AttackRange && attackTimer <= 0 && !isAttacking)
		{
			AttackPlayer();
		}
		else if (!isAttacking)
		{
			// 追踪玩家
			ChasePlayer();
		}
	}
	
	private void ChasePlayer()
	{
		// 获取玩家的实际碰撞体位置
		CollisionShape2D playerCollision = player.GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 playerActualPosition = player.GlobalPosition + playerCollision.Position;
		
		// 获取敌人的实际碰撞体位置
		CollisionShape2D enemyCollision = GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 enemyActualPosition = GlobalPosition + enemyCollision.Position;
		
		// 计算朝向玩家实际位置的方向
		Vector2 direction = (playerActualPosition - enemyActualPosition).Normalized();
		
		// 设置速度
		Velocity = direction * Speed;
		
		// 根据移动方向翻转精灵
		if (direction.X > 0)
		{
			animatedSprite.FlipH = false;
		}
		else if (direction.X < 0)
		{
			animatedSprite.FlipH = true;
		}
		
		// 播放跑步动画
		if (animatedSprite.Animation != "run")
		{
			animatedSprite.Play("run");
		}
		
		// 移动
		MoveAndSlide();
	}
	
	private void AttackPlayer()
	{
		// 设置攻击状态
		isAttacking = true;
		attackTimer = AttackCooldown;
		
		// 停止移动
		Velocity = Vector2.Zero;
		
		// 获取玩家的实际碰撞体位置
		CollisionShape2D playerCollision = player.GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 playerActualPosition = player.GlobalPosition + playerCollision.Position;
		
		// 获取敌人的实际碰撞体位置
		CollisionShape2D enemyCollision = GetNode<CollisionShape2D>("CollisionShape2D");
		Vector2 enemyActualPosition = GlobalPosition + enemyCollision.Position;
		
		// 面向玩家实际位置
		Vector2 directionToPlayer = (playerActualPosition - enemyActualPosition).Normalized();
		if (directionToPlayer.X > 0)
		{
			animatedSprite.FlipH = false;
		}
		else if (directionToPlayer.X < 0)
		{
			animatedSprite.FlipH = true;
		}
		
		// 播放攻击动画
		animatedSprite.Play("attack_r1");
		
		// 根据朝向调整攻击区域位置
		if (animatedSprite.FlipH)
		{
			attackArea.Position = new Vector2(-attackAreaOffset.X, attackAreaOffset.Y);
		}
		else
		{
			attackArea.Position = attackAreaOffset;
		}
		
		// 启用攻击碰撞
		attackCollision.Disabled = false;
		
		// 设置攻击碰撞在短时间后自动禁用
		GetTree().CreateTimer(0.3f).Timeout += () => {
			attackCollision.Disabled = true;
		};
	}
	
	private void OnHurtBoxAreaEntered(Area2D area)
	{
		// 检查是否是玩家的攻击区域
		if (area.IsInGroup("player_attack"))
		{
			TakeDamage(20); // 可以后续改为从玩家获取攻击力
		}
		// 检查是否是军队的攻击区域
		else if (area.IsInGroup("army_attack"))
		{
			TakeDamage(20); // 军队攻击伤害
		}
	}
	
	public void TakeDamage(int damage)
	{
		currentHealth -= damage;
		currentHealth = Mathf.Max(0, currentHealth);
		
		// 更新血条
		healthBar.Value = currentHealth;
		
		// 受伤闪烁效果
		ShowHitEffect();
		
		// 打印伤害信息
		GD.Print($"敌人受到 {damage} 点伤害，剩余血量: {currentHealth}/{MaxHealth}");
		
		// 检查是否死亡
		if (currentHealth <= 0)
		{
			OnDeath();
		}
	}
	
	private void ShowHitEffect()
	{
		// 创建受伤闪烁效果
		var tween = CreateTween();
		tween.SetParallel(true);
		
		// 闪烁效果：快速变红再恢复
		tween.TweenProperty(animatedSprite, "modulate", new Color(1, 0.3f, 0.3f, 1), 0.1f);
		tween.TweenProperty(animatedSprite, "modulate", new Color(1, 1, 1, 1), 0.1f).SetDelay(0.1f);
	}
	
	private void OnDeath()
	{
		GD.Print("敌人被击败了！");
		
		// 死亡闪烁效果
		var tween = CreateTween();
		tween.TweenProperty(animatedSprite, "modulate", new Color(1, 1, 1, 0.3f), 0.2f);
		tween.TweenProperty(animatedSprite, "modulate", new Color(1, 1, 1, 0), 0.3f);
		
		// 延迟移除节点
		GetTree().CreateTimer(0.5f).Timeout += () => {
			QueueFree();
		};
	}
	
	private void OnAnimationFinished()
	{
		// 当攻击动画播放完成时，重置攻击状态
		if (animatedSprite.Animation == "attack_r1")
		{
			isAttacking = false;
			// 确保攻击碰撞被禁用
			attackCollision.Disabled = true;
			
			// 如果不在攻击范围内，继续追踪
			if (player != null)
			{
				float distanceToPlayer = GlobalPosition.DistanceTo(player.GlobalPosition);
				if (distanceToPlayer > AttackRange)
				{
					animatedSprite.Play("idle");
				}
			}
		}
	}
}
